package com.office.supplies.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.office.supplies.mapper.GoodsMapper;
import com.office.supplies.mapper.SaleMapper;
import com.office.supplies.mapper.StockMapper;
import com.office.supplies.pojo.Goods;
import com.office.supplies.pojo.Sale;
import com.office.supplies.pojo.Stock;
import com.office.supplies.pojo.dto.SelectSaleListDTO;
import com.office.supplies.pojo.vo.SaleGoodsVO;
import com.office.supplies.pojo.vo.SaleListVO;
import com.office.supplies.service.SaleService;
import com.office.supplies.util.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author admin
 * @Description SaleServiceImpl
 * @Date 2023/12/12/12:58
 */
@Service
public class SaleServiceImpl extends ServiceImpl<SaleMapper, Sale> implements SaleService {

    @Autowired
    private SaleMapper saleMapper;

    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 获取所有商品信息和对应的库存
     *
     * @return List<SaleGoodsVO>
     */
    public List<SaleGoodsVO> getGoodsListForSale() {
        return saleMapper.getGoodsListAndCount();
    }

    /**
     * 销售商品
     *
     * @param sale Sale
     */
    @Transactional
    public void saleGoods(Sale sale) {
//        // 库存一定存在，因为销售的商品是从库存动态查询的
//        Stock stock = stockMapper.getGoodsCountByGoodsId(sale.getGoodsId());
//
//        // 判断库存够不够，及 库存数量 >= 销售数量
//        if(stock.getGoodsCount() >= sale.getSaleCount()){
//
//            // 判断是否将库存 = 0
//            if(stock.getGoodsCount() - sale.getSaleCount() == 0){
//                // 删除库存表
//                stockMapper.deleteStockByGoodsId(sale.getGoodsId());
//            }else {
//                // 更新库存表
//                Stock s = Stock.builder()
//                        .goodsId(sale.getGoodsId())
//                        .goodsCount(stock.getGoodsCount() - sale.getSaleCount())
//                        .createDate(new Date())
//                        .build();
//                stockMapper.setGoodsCount(s);
//            }
//            // 最后插入一条销售信息
//            sale.setEmpId(BaseContext.getCurrentId());
//            saleMapper.insertSale(sale);
//
//        }else {
//            throw new RuntimeException("库存不足！请联系采购员！");
//        }
        sale.setEmpId(BaseContext.getCurrentId());
        sale.setStatus(1);
        // 查询商品单价
        Goods goods = goodsMapper.selectById(sale.getGoodsId());
        sale.setPrice(goods.getGoodsPrice());
        sale.setTotalPrice(sale.getPrice() * sale.getSaleCount());
        save(sale);
    }

    /**
     * 查询销售订单
     *
     * @param pageNum           Integer
     * @param pageSize          Integer
     * @param selectSaleListDTO SelectSaleListDTO
     * @return PageInfo<SaleListVO>
     */
    public PageInfo<SaleListVO> getSaleListByPageAndCondtion(Integer pageNum, Integer pageSize,
                                                             SelectSaleListDTO selectSaleListDTO) {
        PageHelper.startPage(pageNum, pageSize);
        List<SaleListVO> selectBuyList = saleMapper.selectSaleInfos(selectSaleListDTO);
        return new PageInfo<>(selectBuyList);
    }

    /**
     * 修改销售订单
     *
     * @param sale Sale
     */
    public void updateSaleInfo(Sale sale) {
        // 只能修改price,totalPrice
        saleMapper.updateSaleInfo(sale);
    }

    /**
     * 删除销售信息
     *
     * @param id Long
     */
    @Transactional
    public void deleteSaleInfo(Long id) {
        // 检查销售申请的状态
        Sale dbSale = getById(id);
        if (dbSale.getStatus() == 2) {
            // 如果是已领取转态，则库存退回
            // 1.查询库存
            Stock stock = stockMapper.getGoodsCountByGoodsId(dbSale.getGoodsId());
            int stockCount = 0;
            int saleCount = 0;
            if (stock != null) {
                stockCount = stock.getGoodsCount();
            }
            saleCount = dbSale.getSaleCount();


            // 2.更新库存
            // 2.1 如果没有库存，则新增库存
            // 库存的回归应该遵循销售单的
            if (stockCount <= 0) {
                stockMapper.insert(
                        new Stock(
                                null,
                                dbSale.getGoodsId(),
                                saleCount,
                                null
                        )
                );
            } else {
                // 2.2 如果有库存，则增加库存
                stockMapper.update(
                        new LambdaUpdateWrapper<Stock>()
                                .set(Stock::getGoodsCount, stockCount + saleCount)
                                .eq(Stock::getGoodsId, dbSale.getGoodsId())
                );
            }
        }

        // 删除销售申请表
        saleMapper.deleteById(id);

    }

    @Override
    @Transactional
    public void pass(Long id) {
        Sale dbSale = getById(id);
        // 要出库的数量
        Integer saleCount = dbSale.getSaleCount();

        Long goodsId = dbSale.getGoodsId();
        Stock stock = stockMapper.selectOne(
                new LambdaQueryWrapper<Stock>()
                        .eq(Stock::getGoodsId, goodsId)
        );

        // 库存数量
        Integer goodsCount = stock.getGoodsCount();

        if (saleCount > goodsCount) {
            throw new RuntimeException("库存不足！");
        }

        if (saleCount == goodsCount) {
            // 删除库存表
            stockMapper.delete(new LambdaQueryWrapper<Stock>().eq(Stock::getGoodsId, goodsId));
        } else if (saleCount < goodsCount) {
            // 更新库存表
            stockMapper.update(
                    new LambdaUpdateWrapper<Stock>()
                            .set(Stock::getGoodsCount, goodsCount - saleCount)
                            .eq(Stock::getGoodsId, goodsId)
            );
        }

        // 更新出库申请表
        lambdaUpdate().set(Sale::getStatus, 2).eq(Sale::getId, id).update();

    }

    @Override
    public void deleteSaleById(Long id) {
        saleMapper.deleteById(id);
    }

}
